package com.mvc.business.service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.base.model.Picture;
import com.mvc.base.service.BaseCompanyManager;
import com.mvc.base.service.CustomerManager;
import com.mvc.base.service.PictureManager;
import com.mvc.business.model.Sample;
import com.mvc.framework.model.Auditable;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-9-4
 */
@Service
public class SampleManager extends BaseCompanyManager<Sample, Integer> {

	@Autowired
	private CustomerManager	  customerManager;

	@Autowired
	private PictureManager	  pictureManager;

	@Autowired
	private SampleItemManager	sampleItemManager;

	public void save(Sample entity) {
		super.save(entity);
	}

	public Sample get(Serializable id) {
		Sample order = super.get(id);
		order.setSampleItems(sampleItemManager.getSampleItemsBySampleId(order.getObjectId()));
		order.setCustomer(customerManager.getByObjectId(order.getCustomerId()));
		order.setPictures(pictureManager.getPicturesByItemIdAndType(order.getObjectId(), Picture.PICTURE_OF_SAMPLE));
		return order;
	}

	public Sample getObject(Integer objectId) {
		Sample order = super.getByObjectId(objectId);
		order.setSampleItems(sampleItemManager.getSampleItemsBySampleId(order.getObjectId()));
		order.setCustomer(customerManager.getByObjectId(order.getCustomerId()));
		order.setCompany(companyManager.getByObjectId(order.getCompanyId()));
		order.setPictures(pictureManager.getPicturesByItemIdAndType(order.getObjectId(), Picture.PICTURE_OF_SAMPLE));
		return order;
	}

	public List<Object> getCount(Integer companyId, Date beginDate, Date endDate) {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createQuery("select count(*) from " + Sample.class.getName()
		        + " where recStatus = ? and companyId=? and invoiceDate >= ? and invoiceDate <= ?");
		query.setParameter(0, Auditable.REC_STATUS_VALID).setParameter(1, companyId).setParameter(2, beginDate).setParameter(3, endDate);
		List<Object> result = query.list();
		session.close();
		return result;
	}

	public List<Object[]> summary(Integer companyId, Date beginDate, Date endDate) {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createQuery("select currency,sum(amount) from " + Sample.class.getName()
		        + " where recStatus = ? and companyId=? and invoiceDate >= ? and invoiceDate <= ? group by currency");
		query.setParameter(0, Auditable.REC_STATUS_VALID).setParameter(1, companyId).setParameter(2, beginDate).setParameter(3, endDate);
		List<Object[]> result = query.list();
		session.close();
		return result;
	}
}
